05. Struct or Variable?

It is time for an exercise called “Struct or Variable?” We'll provide a list of names, then you must decide if you think each item would be better represented as a simple, primitive variable, or a struct.

QUESTION:

Here are the names. What do you think? Struct or variable?

  • library
  • subTitle
  • numberOfPages
  • book
  • weight
  • fictional
ANSWER:

Here’s what we answered:

  • library
    • For library, a bunch of values come to mind. A library can have a name, an address, hours of operation, etc. So given this name, we'd go with a struct.
  • subTitle
    • Subtitles are usually just simple strings. Therefore, it should probably be a String variable.
  • numberOfPages
    • The number of pages is a number. So an Int variable would work fine.
  • book
    • This could swing either way. On one hand, someone might just use the name book for a String variable that contains a book’s title. But if that were the case, then we might want to use a more descriptive name like bookTitle. So in this case, let’s go with struct. A Book struct could contain information like a title, subtitle, number of pages, and so on.
  • weight
    • Weight is usually a single measurement. We'd go with a variable — probably of Double type.
  • fictional
    • This name is indicative of a Bool variable. A book is either fictional or it’s not—true or false.

Valid or Invalid?

For this exercise, let’s take a look at this snippet of code. Some of the lines in this snippet contain errors, but we've removed them to see if you can identify them.

Which lines in this example contain an error?

Which lines in this example contain an error?

QUESTION:

It is your job to indicate which lines in this snippet cause the Swift compiler to complain. Try attempting this without copying the code into a Playground.

ANSWER:

If you said there were errors in braves.name, freddie.hometown, and myFavoriteTeam (lines 17, 19, and 23)—you're right! Read on for more details.